using System.Net;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Web;

namespace Screenshot
{
    public class TranslateUtil
    {
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
        /// <summary>
        /// 使用Get的方式调用百度API进行翻译
        /// </summary>
        /// <param name="content">要转化的文本</param>
        /// <param name="languageFrom">要转化的语言</param>
        /// <param name="languageTo">目标语言</param>
        /// <returns></returns>
        public static string TranslateGet(string content, string languageFrom, string languageTo)
        {
            string appId = "";//APP ID
            Random rd = new Random();
            string salt = rd.Next(100000).ToString();
            string secretKey = "";//密钥
            string sign = EncryptString(appId + content + salt + secretKey);
            string url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
            url += "q=" + HttpUtility.UrlEncode(content);
            url += "&from=" + languageFrom;
            url += "&to=" + languageTo;
            url += "&appid=" + appId;
            url += "&salt=" + salt;
            url += "&sign=" + sign;
            HttpWebRequest? request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
            request.UserAgent = null;
            request.Timeout = 6000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }
        // 计算MD5值
        public static string EncryptString(string str)
        {
            MD5 md5 = MD5.Create();
            // 将字符串转换成字节数组
            byte[] byteOld = Encoding.UTF8.GetBytes(str);
            // 调用加密方法
            byte[] byteNew = md5.ComputeHash(byteOld);
            // 将加密结果转换为字符串
            StringBuilder sb = new StringBuilder();
            foreach (byte b in byteNew)
            {
                // 将字节转换成16进制表示的字符串，
                sb.Append(b.ToString("x2"));
            }
            // 返回加密的字符串
            return sb.ToString();
        }
        /// <summary>
        /// 使用Post的方式调用百度API进行翻译
        /// </summary>
        /// <param name="content">要转化的文本</param>
        /// <param name="languageFrom">要转化的语言</param>
        /// <param name="languageTo">目标语言</param>
        /// <returns></returns>
        public static string TranslatePost(string content, string languageFrom, string languageTo)
        {
            string appId = "";//APP ID
            string passWord = "";//密钥
            string randomNum = new Random().Next().ToString();
            #region 获取MD5加密编码后的小写格式文本
            //System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            //byte[] buffer = md5.ComputeHash(Encoding.UTF8.GetBytes(appId + content + randomNum + passWord));
            //string md5Sign = string.Join("", buffer.Select(x => x.ToString("x2")));//转化为小写
            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                byte[] buffer = md5.ComputeHash(Encoding.UTF8.GetBytes(appId + content + randomNum + passWord));
                string md5Sign = string.Join("", buffer.Select(x => x.ToString("x2")));
                #endregion
                using (WebClient webClient = new WebClient())
                {
                    System.Collections.Specialized.NameValueCollection nameValueCollection = new System.Collections.Specialized.NameValueCollection();
                    nameValueCollection.Add("q", content);
                    nameValueCollection.Add("from", languageFrom);
                    nameValueCollection.Add("to", languageTo);
                    nameValueCollection.Add("appid", appId);
                    nameValueCollection.Add("salt", randomNum);
                    nameValueCollection.Add("sign", md5Sign);
                    string apiUrl = "http://api.fanyi.baidu.com/api/trans/vip/translate";
                    byte[] bytes = webClient.UploadValues(apiUrl, "POST", nameValueCollection);
                    string resultContent = Encoding.UTF8.GetString(bytes);
                    return resultContent;
                }
            }
        }
    }
    /// <summary>
    /// 语言枚举常数
    /// </summary>
    public class Language
    {
        public const string 自动检测 = "auto";
        public const string 中文 = "zh";
        public const string 英语 = "en";
        public const string 粤语 = "yue";
        public const string 文言文 = "wyw";
        public const string 日语 = "jp";
        public const string 韩语 = "kor";
        public const string 法语 = "fra";
        public const string 西班牙语 = "spa";
        public const string 泰语 = "th";
        public const string 阿拉伯语 = "ara";
        public const string 俄语 = "ru";
        public const string 葡萄牙语 = "pt";
        public const string 德语 = "de";
        public const string 意大利语 = "it";
        public const string 希腊语 = "el";
        public const string 荷兰语 = "nl";
        public const string 波兰语 = "pl";
        public const string 保加利亚语 = "bul";
        public const string 爱沙尼亚语 = "est";
        public const string 丹麦语 = "dan";
        public const string 芬兰语 = "fin";
        public const string 捷克语 = "cs";
        public const string 罗马尼亚语 = "rom";
        public const string 斯洛文尼亚语 = "slo";
        public const string 瑞典语 = "swe";
        public const string 匈牙利语 = "hu";
        public const string 繁体中文 = "cht";
        public const string 越南语 = "vie";
    }
    public class TranslationResult
    {
        //转换之前的原文
        public string? Src { get; set; }
        //转换之后的结果
        public string? Dst { get; set; }
    }
    public class RootObject
    {
        //要转化的语言
        public string? From { get; set; }
        //目标语言
        public string? To { get; set; }
        public List<TranslationResult>? Trans_Result { get; set; }
    }
}

